這是一個來自msw的錯誤處理當我們想要驗證是否元件會因為server回傳錯誤的資料而產生錯誤警示
import { useEffect, useState } from 'react';
import axios from 'axios';
type NewsType = {
title: string;
img: string;
};
const News = () => {
const [newsList, setNewsList] = useState<NewsType[]>([]);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const getNews = async () => {
try {
const news = await axios.get('http://localhost:5000/news');
} catch (error) {
setError('SERVER ERROR');
}
};
getNews();
}, []);
return (
<div>
{newsList.length > 0
? newsList.map((news) => {
return (
<div key={news.title} role="news">
{news.title}
</div>
);
})
: null}
{error ? <div role="error">{error}</div> : null}
</div>
);
};
export default News;
那我們如何透過msw回傳一個錯誤的狀態碼來讓前端的component接收到catch
import { render, screen } from '@testing-library/react';
import { rest } from 'msw';
import News from '../News';
import { server } from '../../../mocks/server';
describe('<Users />', () => {
test('should component show error message', async () => {
server.resetHandlers(
rest.get('http://localhost:5000/news', (req, res, ctx) => {
return res(ctx.status(400));
})
);
render(<News />);
const error = await screen.findByRole('error');
expect(error).toBeInTheDocument();
});
});
這邊我們就驗證當我們回傳一個錯誤訊息時,component的catch會抓到error進而產生錯誤訊息,這時我們可以重新resetHandler複寫一個錯誤的response讓測試的元件接收到statusCode(400)的錯誤
接下來使用tobeIndocument來驗證